/**
 * Copyright (c) 2009.kingbi.
 * All rights reserved.
 */

package com.kingbi.system.role.jsfBean;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.kingbi.system.function.model.FunctionModel;
import com.kingbi.system.function.service.FunctionService;
import com.kingbi.system.role.model.RoleModel;
import com.kingbi.system.role.service.RoleHelper;
import com.kingbi.system.role.service.RoleService;
import com.kingbi.system.roleFunction.model.RoleFunctionModel;
import com.kingbi.system.roleFunction.model.RoleFunction_ID;
import com.kingbi.system.roleFunction.service.RoleFunctionService;

/**
 * Class description goes here.
 * 
 * Created by Auto Code Produce System User: Date: 20091026 Time: 153912
 */
public class RoleJsfBean extends RoleDataBean
{
    // 页面导航
    private String outcome;

    // 错误信息提示
    FacesMessage message;

    // //加载角色service
    RoleService roleService;

    // //加载功能service
    FunctionService functionService;

    // 加载功能角色关联service
    RoleFunctionService roleFunctionService;
    
    

    static Logger logger = Logger.getLogger(RoleJsfBean.class);

    public void setRoleService(RoleService roleService)
    {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance()
                .getExternalContext().getRequest();
        String searchTag = (String) request.getParameter("searchTag");

        this.roleService = roleService;

        if(searchTag != null && searchTag.equals("isSearch"))
        {
            search();
        }
    }

    public void setFunctionService(FunctionService functionService)
    {
        this.functionService = functionService;
    }

    public void setRoleFunctionService(RoleFunctionService roleFunctionService)
    {
        this.roleFunctionService = roleFunctionService;
    }

    /**
     * 页面导航
     * 
     * @return
     */
    public String outcome()
    {
        logger.warn("outcomeoutcome");
        return outcome;
    }

    /**
     * 导向添加页面
     * 
     * @return
     */
    public String preAdd()
    {
        getEmptyJsfBean();

//        /*
//         * 读取功能列表
//         */
//        tData = null;
//        selected = null;
//        FunctionModel funModel = new FunctionModel();
//        try
//        {
//            setFunctionList(functionService.listFunction(funModel, 0, 100));
//        }
//        catch (Exception e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        logger.warn("**********************perAdd()");

        return "addRole";
    }

    /**
     * 导向修改页面
     * 
     * @return
     */
    public String preUpdate()
    {

        logger.warn("**********************perUpdate()");
        try
        {
            int n = tData.getRowCount();
            for (int i = 0; i < n; i++)
            {
                tData.setRowIndex(i);
                if(selected.isSelected())
                {
                    setChecked(false);
                    RoleModel tempModel = new RoleModel();
                    tempModel = (RoleModel) tData.getRowData();
                    RoleModel updateModel = new RoleModel();
                    updateModel = roleService.loadRole(tempModel.getRoleID());
                    
                    /*
                     * 构造已选功能
                     */
                    RoleFunctionModel search_roleFunModel = new RoleFunctionModel();
                    
                    RoleFunction_ID roleFunID = new RoleFunction_ID();
                    roleFunID.setRoleCode(updateModel.getRoleCode());
                    
                    search_roleFunModel.setRoleFunID(roleFunID);
                    List<RoleFunctionModel> roleFunList = null;
                    roleFunList = roleFunctionService.listRoleFunction(search_roleFunModel, 0, 100);
                    String funCodeBudStr = "";
                    if(roleFunList!=null && roleFunList.size()>0)
                    {
                        StringBuffer funCodeBuf = new StringBuffer();
                        StringBuffer roleRight = new StringBuffer();
                        funCodeBuf.append("[");
                        for(int ri=0;ri<roleFunList.size();ri++)
                        {
                            RoleFunctionModel roleFunModel = new RoleFunctionModel();
                            roleFunModel = roleFunList.get(ri);
                            funCodeBuf.append("[");
                            funCodeBuf.append("'"+roleFunModel.getRoleFunID().getFunctionCode()+"',");
                            funCodeBuf.append("'"+roleFunModel.getRoleRight()+"'");
                            funCodeBuf.append("],");
                            
                            roleRight.append(roleFunModel.getRoleFunID().getFunctionCode() +"~");
                            roleRight.append("".equals(roleFunModel.getRoleRight())?"-1,":roleFunModel.getRoleRight() +",");
                        }
                        funCodeBudStr = funCodeBuf.toString();
                        funCodeBudStr = funCodeBudStr.substring(0, funCodeBudStr.length()-1)+"]";
                        
                        this.setThisRoleFunRight(roleRight.toString());
                    }
                    setRoleFunArray(funCodeBudStr);
                    getJsfDataBean(updateModel);
                }
            }

        }
        catch (Exception e)
        {
            return "failure";
        }
        logger.warn("********************************");
        return "updateRole";
    }

    /**
     * 提交添加或修改操作
     * 
     * @return
     * @throws SQLException 
     */
    public String save() throws SQLException
    {
        logger.warn("**********************save()");
        /*
         * 添加角色Model
         */
        RoleModel roleModel = new RoleModel();
        roleModel = super.getJsfModel();
        
        //--获取添加还是修改
        String operaFlag = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("operaFlag");
        if("add".equals(operaFlag)){
        	roleModel.setRoleID(roleService.getMaxId()+1);
        	roleModel.setRoleCode(roleService.getMaxRoleId());
        }else if("update".equals(operaFlag)){
        	roleModel.setRoleID(this.getRoleID());
        }
        
        try
        {
            roleService.saveRole(roleModel,this.getThisRoleFunRight());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        getEmptyJsfBean();
        search();
        return "success";
    }

    /**
     * 删除
     * 
     * @return
     */
    public String delete()
    {
        try
        {
            int n = tData.getRowCount();
            for (int i = 0; i < n; i++)
            {
                tData.setRowIndex(i);
                if(selected.isSelected())
                {
                    setChecked(false);
                    RoleModel tempModel = new RoleModel();
                    tempModel = (RoleModel) tData.getRowData();
                    roleService.deleteRole(tempModel.getRoleID());
                    selected.setSelected(false);
                }
            }
            getEmptyJsfBean();
            search();
        }
        catch (Exception e)
        {
            return "failure";
        }
        return "success";
    }

    /**
     * 显示详细信息
     * 
     * @return
     */
    public String show()
    {
        try
        {
            FacesContext context = FacesContext.getCurrentInstance();
            String value = (String) context.getExternalContext().getRequestParameterMap().get(
                    "roleID");
            int i_roleID = 0;
            if(value!=null && !value.equals("") && !value.equals("null"))
            {
                i_roleID = Integer.parseInt(value);
            }
            RoleModel updateModel = new RoleModel();
            updateModel = roleService.loadRole(i_roleID);
            getJsfDataBean(updateModel);
            return "showRole";

        }
        catch (Exception e)
        {
            return "failure";
        }

    }

    /**
     * 从其它页面返回到查询列表页面
     * 
     * @return
     */
    public String backToSearch()
    {
        getEmptyJsfBean();
        search();
        return "success";
    }

    /**
     * 查询方法
     * 
     * @return
     */
    public String search()
    {
        tData = null;
        selected = null;
        logger.warn("**********************search()");
        String s_new_CurrentPage = (String) FacesContext.getCurrentInstance().getExternalContext()
                .getRequestParameterMap().get("newCurrentPage");
        String s_query_flag = (String) FacesContext.getCurrentInstance().getExternalContext()
                .getRequestParameterMap().get("queryFlag");
        //功能管理、浏览权限标识
        String s_funRight = (String) FacesContext.getCurrentInstance().getExternalContext()
        .getRequestParameterMap().get("funRight");
        //列表页面提交查询标识
        String s_searchFlag = (String) FacesContext.getCurrentInstance().getExternalContext()
        .getRequestParameterMap().get("searchFlag");
        if(s_funRight!=null && !s_funRight.equals("") && !s_funRight.equals("null"))
        {
            setMagFlag(s_funRight);
        }

        RoleModel roleModel = new RoleModel();
        roleModel = super.getJsfModel();
        if(s_query_flag != null && s_query_flag.equals("ispage"))
        {
            listUpdateFlag = false;
        }
        else
        {
            listUpdateFlag = true;
            listUpdateFlag = true;
            if(!(s_searchFlag!=null && s_searchFlag.equals("isListSearch")))
            {
                getEmptyJsfBean();
            }        
        }

       

        /*
         * 总记录数
         */
        if(listUpdateFlag)
        {
            setRecordCount(roleService.queryCount(roleModel));
        }
        /*
         * 当前页号
         */
        if(s_new_CurrentPage != null && !s_new_CurrentPage.equals("")
                && !s_new_CurrentPage.equals("null"))
        {
            if(!(s_new_CurrentPage.equals("newPage")))
            {
                setCurrentPage(Integer.parseInt(s_new_CurrentPage));
            }
        }
        else
        {
            setCurrentPage(1);
        }
        /*
         * 处理分页
         */
        dealPage(getRecordCount(), getPageRecord(), getCurrentPage());
        /*
         * 根据分页获取数据记录
         */
        try
        {
        	setStartRecordNum(((getCurrentPage() - 1) * getPageRecord() + 1) < 0 ? 0 : (getCurrentPage() - 1) * getPageRecord() + 1);
			setEndRecordNum(getPageRecord() * getCurrentPage());
            setItems(roleService.listRole(roleModel, (getCurrentPage() - 1) * getPageRecord() + 1,
                    getPageRecord()));
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return "success";
    }

    public void validateRoleCode(FacesContext context, UIComponent component, Object obj)
            throws ValidatorException
    {
        try
        {
            List<RoleModel> roleList = null;
            roleList = roleService.loadRoleByCode(obj.toString());
            if(roleList!=null && roleList.size()>0)
            {
                throw new ValidatorException(new FacesMessage("roleCode", "角色编码重复--请重新填写标识"));
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    public String getDtree()
    {
        RoleHelper roleHel = RoleHelper.getInstance(roleService,functionService,roleFunctionService);
        try
        {
            this.setDtree(roleHel.createFunctionTree());
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }

        return super.getDtree();
    }

}
